package com.platform.usercenter.teamfc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.platform.common.core.constant.Constants;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.utils.StringUtils;
import com.platform.usercenter.domain.SysMenuTreeDTO;
import com.platform.usercenter.domain.vo.MetaVo;
import com.platform.usercenter.teamfc.domain.dto.RouterDTO;
import com.platform.usercenter.teamfc.mapper.SysMenuFcMapper;
import com.platform.usercenter.teamfc.service.SysMenuFcService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author twd
 * @date 2023/10/2 20:10
 */
@Service
public class SysMenuFcServiceImpl implements SysMenuFcService {

    @Resource
    private SysMenuFcMapper sysMenuFcMapper;


    @Override
    public List<SysMenuTreeDTO> selectMenuByIds(Long[] ids) {
        return sysMenuFcMapper.selectMenuListByIds(ids);
    }

    @Override
    public List<RouterDTO> buildMenusPcNew(List<SysMenuTreeDTO> menus, String host, String endPoint, Long rootId) {
        List<RouterDTO> routers = new LinkedList<>();
        for (SysMenuTreeDTO menu : menus) {
            if (!"inner_system".equals(menu.getSystemType())) {
                continue;
            }
            RouterDTO router = new RouterDTO();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu, rootId));


            router.setComponent(getComponent(menu, rootId));
            router.setQuery(menu.getQuery());

            router.setMenuId(menu.getMenuId());
            router.setpId(menu.getParentId());

            String hostIp = null;
            if (StringUtils.isNotEmpty(host)) {
                hostIp = host.replaceAll("%3A", ":").replaceAll("%2F", "/")  //过滤URL 包含中文
                        .replaceAll("%3F", "?").replaceAll("%3D", "=").replaceAll(
                                "%26", "&");
            }

            String path = StringUtils.replaceEach(menu.getPath(), new String[]{"${host}"},
                    new String[]{hostIp});

            if ("0".equals(menu.getIsFrame()) && UserConstants.TYPE_MENU.equals(menu.getMenuType())) {
                router.setPath(path);
            } else {
                router.setPath(getRouterPath(menu, rootId));
            }

            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), path));
            List<SysMenuTreeDTO> cMenus = menu.getChildren();
            if (CollectionUtil.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenusPcNew(cMenus, host, endPoint, rootId));
            } else if (isMenuFrame(menu, rootId)) {
                router.setMeta(null);
                List<RouterDTO> childrenList = new ArrayList<>();
                RouterDTO children = new RouterDTO();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == rootId && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterDTO> childrenList = new ArrayList<>();
                RouterDTO children = new RouterDTO();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu   菜单信息
     * @param rootId
     * @return 路由名称
     */
    public String getRouteName(SysMenuTreeDTO menu, Long rootId) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu, rootId)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu   菜单信息
     * @param rootId
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuTreeDTO menu, Long rootId) {
        return menu.getParentId().intValue() == rootId && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 获取组件信息
     *
     * @param menu   菜单信息
     * @param rootId
     * @return 组件信息
     */
    public String getComponent(SysMenuTreeDTO menu, Long rootId) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu, rootId)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != rootId && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu, rootId)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu   菜单信息
     * @param rootId
     * @return 结果
     */
    public boolean isParentView(SysMenuTreeDTO menu, Long rootId) {
        return menu.getParentId().intValue() != rootId && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuTreeDTO menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 获取路由地址
     *
     * @param menu   菜单信息
     * @param rootId
     * @return 路由地址
     */
    public String getRouterPath(SysMenuTreeDTO menu, Long rootId) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != rootId && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu, rootId)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".",
                        "/%23/", "/#/", "?", "=", "&", "${host}"},
                new String[]{"", "", "", "/", "/", "/", "", "/", "/", "host"});
    }
}
